<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Loader extends CI_Loader {

    /**
     * List of loaded services
     *
     * @var array
     * @access protected
     */
    protected $_ci_services = array();

    /**
     * List of paths to load services from
     *
     * @var array
     * @access protected
     */
    protected $_ci_service_paths = array();

    /**
     *
     * 定义service文件夹名称  （注意点一）
     *
     */
    protected $_ci_service_dir_name = 'services';

    /**
     * Constructor
     *
     * Set the path to the Service files
     */
    public function __construct() {

        parent::__construct();
        load_class('Service', 'core');
        $this->_ci_service_paths = array(APPPATH);
    }

    /**
     * Service Loader
     *
     *
     * @param string    the name of the class
     * @param mixed    the optional parameters
     * @param string    an optional object name
     * @return    boolean
     */
    public function service($service = '', $params = null, $object_name = null) {
        if (is_array($service)) {
            foreach ($service as $class) {
                $this->service($class, $params);
            }

            return true;
        }

        if ($service == '' or isset($this->_ci_services[$service])) {
            return false;
        }

        if (!is_null($params) && !is_array($params)) {
            $params = null;
        }

        $subDir = '';


        if (($last_slash = strrpos($service, '/')) !== false) {

            $subDir = substr($service, 0, $last_slash + 1);

            // And the service name behind it
            $service = substr($service, $last_slash + 1);
        }
        $service = ucfirst($service);
        foreach ($this->_ci_service_paths as $path) {

            $filepath = $path . $this->_ci_service_dir_name . '/' . $subDir . $service . '.php';

            if (!file_exists($filepath)) {
                continue;
            }

            include_once($filepath);

            $service = strtolower($service);

            if (empty($object_name)) {
                $object_name = $service;
            }

            $service = ucfirst($service);
            $CI = &get_instance();
            if ($params !== null) {
                $CI->$object_name = new $service($params);
            } else {
                $CI->$object_name = new $service();
            }

            $this->_ci_services[] = $object_name;

            return true;
        }


        return true;
    }

}
